//
//  AppDelegate.m
//  KunLun
//
//  Created by Mac on 2017/11/25.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//
//添加扩展消息 需要注意打包时候在EaseMessageViewController  _sendMessage 修改方法
//message.ext = @{@"name":@"mac pro test"};
#import "AppDelegate.h"
#import "STUserManger.h"
#import "KLLoginViewController.h"
#import "KLTabbarViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import <UserNotifications/UserNotifications.h>
#import "JPUSHService.h"
#import "KLMessageListViewController.h"
#import "KLNewShouruViewController.h"
@interface AppDelegate ()<WXApiDelegate,EMChatManagerDelegate,JPUSHRegisterDelegate,EMClientDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [SVProgressHUD setMaximumDismissTimeInterval:2];    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [KLTabbarViewController new];
    [self.window makeKeyAndVisible];

    //全局
    [[STNoresultView appearance] setBorderColor:KL_BlueBackGroundColor];
//    if (![STUserManger defult].token.length) {
//        self.window.rootViewController = [[STNavigationController alloc] initWithRootViewController:[KLLoginViewController new]];
//    }
    //环信
    EMOptions *options = [EMOptions optionsWithAppkey:IM_appKey];
    [[EMClient sharedClient] addDelegate:self delegateQueue:dispatch_get_main_queue()];
#ifdef DEBUG
    options.apnsCertName = @"kunlun_debug_push_p12";
#else
    options.apnsCertName = @"kunlun_release_push_p12";
#endif

    [[EMClient sharedClient] initializeSDKWithOptions:options];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self configIMPush];
        
    });
    [self configJpush:launchOptions];
    //本地通知
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    //微信
    bool success =   [WXApi registerApp:wechatID];
 
    NSString * phone = [STUserManger defult].phone;
    if (phone.length) {
        [[EMClient sharedClient] loginWithUsername:phone password:EMClientPassword completion:^(NSString *aUsername, EMError *aError) {
            
        }];
    }

    
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    //支付宝
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:aliPayHandleNotifacation object:resultDic];
            NSString * status = resultDic[@"resultStatus"];
            if ([status isEqualToString:@"9000"]) {
                [SVProgressHUD showSuccessWithStatus:[self hudFromCode:status]];
            }else{
                [SVProgressHUD showErrorWithStatus:[self hudFromCode:status]];
            }
        }];
    }
    //微信
   return [WXApi handleOpenURL:url delegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[EMClient sharedClient] applicationDidEnterBackground:application];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark --Private Method
//处理支付宝
- (NSString*)hudFromCode:(NSString*)code{
    if ([code isEqualToString:@"9000"]) {
        return @"支付成功";
    }
    if ([code isEqualToString:@"8000"]) {
        return @"正在处理中";
    }
    if ([code isEqualToString:@"4000"]) {
        return @"订单支付失败";
    }
    if ([code isEqualToString:@"5000"]) {
        return @"重复请求，支付失败";
    }
    if ([code isEqualToString:@"6001"]) {
        return @"中途取消，支付失败";
    }
    if ([code isEqualToString:@"6002"]) {
        return @"网络连接错误";
    }
    if ([code isEqualToString:@"6004"]) {
        return @"支付结果未知";
    }
    return @"未知错误";
}
#pragma mark --WXApiDelegate
- (void)onResp:(BaseResp*)resp{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * loginresp = (SendAuthResp*)resp;
        NSString * token = loginresp.code;
        NSLog(@"%d",loginresp.errCode);
        NSLog(@"%@",token);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信登录"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝了微信登录"];
        }
        if (resp.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信登录成功"];
        }
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp * share = (SendMessageToWXResp*)resp;
        NSLog(@"%d",share.errCode);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信分享"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信分享"];
        }
        if (resp.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信分享成功"];
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp * pay = (PayResp*)resp;
        NSLog(@"%d",pay.errCode);
        if (pay.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信支付"];
        }
        if (pay.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信支付"];
        }
        if (pay.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信支付成功"];
        }
    }
    
}
- (void)configIMPush{
    UIApplication *application = [UIApplication sharedApplication];
    
    //iOS10 注册APNs
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError *error) {
            if (granted) {
#if !TARGET_IPHONE_SIMULATOR
                [application registerForRemoteNotifications];
#endif
            }
        }];
        return;
    }
    
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
#if !TARGET_IPHONE_SIMULATOR
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
#endif
    

}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
    [JPUSHService registerDeviceToken:deviceToken];
    self.registrationID = [JPUSHService registrationID];
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    self.token = token;
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error -- %@",error);
}
#pragma mark --EMChatManagerDelegate
- (void)messagesDidReceive:(NSArray *)aMessages{
    UILocalNotification *localNote = [[UILocalNotification alloc] init];
    
    EMMessage * message = aMessages.lastObject;
  //  NSDictionary * dic = @{@"name":name,@"iconUrl":iconUrl,@"":userID};
    NSDictionary * dic = message.ext;
    if ([message.body isKindOfClass:[EMTextMessageBody class]] && dic) {
        EMTextMessageBody * body = (id)message.body;
        NSString * name = dic[@"name"];
        NSString * alert = [NSString stringWithFormat:@"%@:%@",name,body.text];
        // 1.1.设置通知发出的时间
        localNote.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
        // 1.2.设置通知内容
        localNote.alertBody = alert;
        // 1.3.设置锁屏时,字体下方显示的一个文字
        localNote.alertAction = alert;
        localNote.hasAction = YES;
        // 1.4.设置启动图片(通过通知打开的)
        localNote.alertLaunchImage = @"../Documents/1.jpg";
        // 1.5.设置通过到来的声音
        localNote.soundName = UILocalNotificationDefaultSoundName;
        // 1.6.设置应用图标左上角显示的数字
        localNote.applicationIconBadgeNumber = 1;
       ;
        // 1.7.设置一些额外的信息
        localNote.userInfo = @{@"name" : name, @"type" : @"em"};
        // 2.执行通知
        [[UIApplication sharedApplication] scheduleLocalNotification:localNote];
    }
   
}

- (void)configJpush:(id)launchOptions{
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    
#ifdef DEBUG
    [JPUSHService setupWithOption:launchOptions
                           appKey:jpushAppKey
                          channel:@"noren"
                 apsForProduction:0];
#else
    [JPUSHService setupWithOption:launchOptions
                           appKey:jpushAppKey
                          channel:@"noren"
                 apsForProduction:1];
#endif
    
    
    
}


#pragma mark --极光低版本推送
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
#pragma mark- JPUSHRegisterDelegate
//前台
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler{
    
    NSDictionary * userInfo = notification.request.content.userInfo;

    if ([userInfo.allKeys containsObject:@"type"]) {
        if ([userInfo[@"type"] isEqualToString:@"kunlun"]) {
            UITabBarController * tabbar = (id)self.window.rootViewController;
            if ([tabbar isKindOfClass:[UITabBarController class]]) {
                //
                UINavigationController * nav = tabbar.childViewControllers[tabbar.selectedIndex];
                KLNewShouruViewController * vc = [KLNewShouruViewController new];
                [nav.childViewControllers.lastObject showAlertCancelAndConfirm:@"您收到一个订单，去看看吗?" andWithBlock:^(NSString *name) {
                    if ([name isEqualToString:@"确认"]) {
                        [nav pushViewController:vc animated:YES];
                    }
                }];
              
            }
        }else{
            //消息
            UITabBarController * tabbar = (id)self.window.rootViewController;
            if ([tabbar isKindOfClass:[UITabBarController class]]) {
                //
                UINavigationController * nav = tabbar.childViewControllers[tabbar.selectedIndex];
                KLMessageListViewController * vc = [KLMessageListViewController new];
                //[nav pushViewController:vc animated:YES];
            }
        }
        
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    
    
}
//关闭状态
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if ([userInfo.allKeys containsObject:@"type"]) {
        if ([userInfo[@"type"] isEqualToString:@"kunlun"]) {
            UITabBarController * tabbar = (id)self.window.rootViewController;
            if ([tabbar isKindOfClass:[UITabBarController class]]) {
                //
                UINavigationController * nav = tabbar.childViewControllers[tabbar.selectedIndex];
                KLNewShouruViewController * vc = [KLNewShouruViewController new];
                [nav pushViewController:vc animated:YES];
            }
        }else{
            //消息
            UITabBarController * tabbar = (id)self.window.rootViewController;
            if ([tabbar isKindOfClass:[UITabBarController class]]) {
                //
                UINavigationController * nav = tabbar.childViewControllers[tabbar.selectedIndex];
                KLMessageListViewController * vc = [KLMessageListViewController new];
                [nav pushViewController:vc animated:YES];
            }
        }

    }
    completionHandler();
    
}
#pragma mark --EMClientDelegate
- (void)userAccountDidLoginFromOtherDevice{
    UITabBarController * tabbar = (id)self.window.rootViewController;
    if ([tabbar isKindOfClass:[UITabBarController class]]) {
        //
        UINavigationController * nav = tabbar.childViewControllers[tabbar.selectedIndex];
        UIViewController * vc = nav.childViewControllers.lastObject;
        [vc showAlert:@"您的账号已经在其他设备登录，请重新登录" andWithBlock:^(NSString *name) {
            if ([name isEqualToString:@"确认"]) {
                [[STUserManger defult] removeUserPreferce];
                [UIApplication sharedApplication].keyWindow.rootViewController = [[STNavigationController alloc] initWithRootViewController:[KLLoginViewController new]];
                [[UIApplication sharedApplication].keyWindow st_showAnimationWithType:STAnimationTypeoglFlip];
            }
        }];
        
        
        
    }
}
@end
